#include <windows.h>
#include <chrono>

#include "util.h"


#define DCM_ORG_ROOT                        "1.2.826.0.1.3680043.10.1100"

std::string
Util::GBK2UTF8(
    const std::string&               aStr
)
{
    UINT CP_GBK = 936;
    int len = MultiByteToWideChar(CP_GBK, 0, aStr.c_str(), -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len + 1];
    memset(wstr, 0, len + 1);
    MultiByteToWideChar(CP_GBK, 0, aStr.c_str(), -1, wstr, len);
    len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* str = new char[len + 1];
    memset(str, 0, len + 1);
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
    std::string strTemp = str;
    if (wstr) delete[] wstr;
    if (str) delete[] str;
    return strTemp;
}

std::string
Util::UTF82GBK(
    const std::string&                   aStr
)
{
    UINT CP_GBK = 936;
    int len = MultiByteToWideChar(CP_UTF8, 0, aStr.c_str(), -1, NULL, 0);
    wchar_t* wszGBK = new wchar_t[len + 1];
    memset(wszGBK, 0, len * 2 + 2);
    MultiByteToWideChar(CP_UTF8, 0, aStr.c_str(), -1, wszGBK, len);
    len = WideCharToMultiByte(CP_GBK, 0, wszGBK, -1, NULL, 0, NULL, NULL);
    char* szGBK = new char[len + 1];
    memset(szGBK, 0, len + 1);
    WideCharToMultiByte(CP_GBK, 0, wszGBK, -1, szGBK, len, NULL, NULL);
    std::string strTemp(szGBK);
    if (wszGBK) delete[] wszGBK;
    if (szGBK) delete[] szGBK;
    return strTemp;
}

std::string
Util::GenerateUid()
{
    auto clock = std::chrono::system_clock::now();
    long long count = std::chrono::duration_cast<std::chrono::milliseconds>(clock.time_since_epoch()).count();
    Sleep(1);
    return DCM_ORG_ROOT + std::string(".") + std::to_string(count);
}
